package GUI.gameLobbyWin;

import gamePlus.GameSettings;
import gamePlus.client.Client;
import gamePlus.server.GameClientSlot;

import java.awt.Dimension;
import java.io.IOException;
import java.util.LinkedList;

import javax.swing.BoxLayout;
import javax.swing.JFrame;

import GUI.menuWin.MainFrame;

import protocol.Message;

@SuppressWarnings("serial")
public class GameLobbyWindow extends JFrame {
	private static GameLobbyWindow instance;
	private Client client;
	
	private LobbyMainPanel mainPanel;
	
	public GameLobbyWindow(String serverName, Client client) {
		this.client=client;
		mainPanel = new LobbyMainPanel();
		mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.LINE_AXIS));
		setContentPane(mainPanel);
		setVisible(true);
		setTitle(serverName);
		setMinimumSize(new Dimension(800, 600));
		setResizable(false);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		instance = this;
	}
	
	public void updateSlots(GameClientSlot[] gcSlots) {
		mainPanel.updateSlots(gcSlots);
	}
	
	public static GameLobbyWindow getInstance() {
		return instance;
	}
	
	void sendMessage(String message) {
		try {
			client.sendMessage(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void acceptMessage(Message message) {
		mainPanel.acceptMessage(message);
	}
	
	public void syncMessages(LinkedList<Message> messages) {
		mainPanel.syncMessages(messages);
	}
	
	void requestSyncMessages() {
		try {
			client.requestSyncMessages();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void updateSettings(GameSettings serverSettings) {
		mainPanel.updateSettings(serverSettings);
	}
	
	void newSettings(GameSettings serverSettings) {
		client.newSettings(serverSettings);
	}

	boolean isAdmin() {
		return client.isAdmin();
	}

	public void becameAdministrator() {
		mainPanel.becameAdministrator();
	}

	void editingSettings(GameSettings serverSettings) {
		mainPanel.editingSettings(serverSettings);
	}
	
	void finishedEditingSettings() {
		mainPanel.finishedEditingSettings();
	}

	public void dispose() {
		doExit();
	}
	
	public void doExit() {
		super.dispose();
		client.doExit();
		MainFrame.showWindow();
		GameLobbyWindow.instance=null;
	}
	
	boolean amIReady() {
		return mainPanel.amIReady();
	}
	
	void setReady(boolean ready) {
		client.setReady(ready);
	}
	
	void kickPlayer(String playerName) {
		client.kickPlayer(playerName);
	}

	void changedSlot(int slotNum, int selectedIndex) {
		client.changedSlot(slotNum, selectedIndex);
	}

	void switchSlot(int slotNum, boolean up) {
		client.switchSlot(slotNum, up);
	}
	
	void startTheGame() {
		client.startTheGame();
	}
}
